# -*- coding: utf-8 -*-

import json
import sys

from .object import CommandBase, GameState


def parse_input_state(input_data: str) -> GameState:
    """解析输入状态

    Args:
        input_data: 输入的JSON字符串

    Returns:
        解析后的输入状态
    """
    try:
        input_state = json.loads(input_data.strip())
        return GameState(input_state)
    except json.JSONDecodeError as e:
        print(f'JSON解析错误: {e}', file=sys.stderr)
        return {}


def format_output_commands(commands: list[CommandBase]) -> str:
    """格式化输出命令

    Args:
        commands: 命令列表

    Returns:
        格式化的JSON字符串
    """
    try:
        cmds = [cmd.toDict() for cmd in commands]
        return json.dumps(cmds, ensure_ascii=False, separators=(',', ':'))
    except Exception as e:
        print(f'JSON序列化错误: {e}', file=sys.stderr)
        return '[]'


def input(filepath: str) -> str:
    with open(filepath, 'r', encoding='utf-8') as f:
        return f.read()


def output(s: str, file=sys.stdout, is_commands=False):
    # 为commands输出添加特殊标识前缀
    if file == sys.stdout and is_commands:
        print(f"COMMANDS_OUTPUT:{s}", file=file, flush=True)
    else:
        print(s, file=file, flush=True)
